package cn.mabach.oauth2;

import cn.mabach.oauth2.validateCode.imageCode.ValidateCodeGenerator;
import cn.mabach.oauth2.validateCode.imageCode.ValidateCodeGeneratorImpl;
import cn.mabach.oauth2.validateCode.smsCode.SendCodeImpl;
import cn.mabach.oauth2.properties.SecurityProperties;
import cn.mabach.oauth2.validateCode.smsCode.SendCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import org.springframework.security.web.firewall.HttpFirewall;
import org.springframework.security.web.firewall.StrictHttpFirewall;
import org.springframework.web.client.RestTemplate;

import javax.sql.DataSource;

/**
 * @Author: ming
 * @Date: 2020/2/5 0005 下午 6:38
 */
@Configuration
@EnableConfigurationProperties(SecurityProperties.class)
public class ConfigBean {
    @Autowired
    private DataSource dataSource;

    //配置rememberMe
    @Bean
    public PersistentTokenRepository persistentTokenRepository() {
        JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
        tokenRepository.setDataSource(dataSource);
        return tokenRepository;
    }

    @Bean // 将提页面exception示信息改为中文
    public ReloadableResourceBundleMessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("classpath:org/springframework/security/messages_zh_CN");
        return messageSource;
    }

    @Bean(name = "restTemplate")
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

//可以实现ValidateCodeGenerator定制验图形证码bean
    @Bean
    @ConditionalOnMissingBean(ValidateCodeGenerator.class)
    public ValidateCodeGenerator imageCodeGenerator() {
        return new ValidateCodeGeneratorImpl();
    }
//可以实现SendCode接口定制短信验证码
    @Bean
    @ConditionalOnMissingBean(SendCode.class)
    public SendCode codeGenerator() {
        return new SendCodeImpl();
    }

    //此处可添加别的规则,目前只设置 允许双 //
    @Bean
    public HttpFirewall allowUrlEncodedSlashHttpFirewall() {
        StrictHttpFirewall firewall = new StrictHttpFirewall();
        firewall.setAllowUrlEncodedDoubleSlash(true);
        return firewall;
    }



}
